#region using

using System;
using System.Text;
using System.Web;
using System.Web.UI;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core;

#endregion

/// <summary>
/// Breaks a post where [addilang] is found in the body and adds a link to full post.
/// </summary>
[Extension("Breaks a post where [addilang] is found and adds a link to the full post with both languages", "0.1", "<a href=\"http://codeplex.com/blogengineaddilang\">Jonas Andersson</a>")]
public class AdditionalLanguage
{
    static protected ExtensionSettings _settings = null;

    /// <summary>
    /// Hooks up an event handler to the Post.Serving event.
    /// </summary>
    public AdditionalLanguage()
    {
        Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);

        // create settings object. You need to pass exactly your
        // extension class name (case sencitive)
        ExtensionSettings settings = new ExtensionSettings("AdditionalLanguage");

        settings.AddParameter("alternatelanguagetext", "\"Also available in\"-text", 80, true, true);
        settings.AddParameter("flag", "The name on a flag-file in /pics/flags");
        settings.IsScalar = true;

        settings.UpdateScalarValue("alternatelanguagetext", "This article is also available in English!");
	settings.UpdateScalarValue("flag", "gb.png");

        // describe specific rules for entering parameters
        settings.Help = "Settings for the Additional Language Extension";
        //------------------------------------------------------
        ExtensionManager.ImportSettings(settings);
        _settings = ExtensionManager.GetSettings("AdditionalLanguage");
    }

    /// <summary>
    /// Handles the Post.Serving event to take care of the [addilang] keyword.
    /// </summary>
    private void Post_Serving(object sender, ServingEventArgs e)
    {
        if (!e.Body.Contains("[addilang]"))
            return;

        if (e.Location == ServingLocation.PostList || e.Location == ServingLocation.Feed)
        {
            AddAddiLangLink(sender, e);
        }
        else if (e.Location == ServingLocation.SinglePost)
        {
            PrepareFullPost(e);
        }
        //else if (e.Location == ServingLocation.Feed)
        //{
        //    e.Body = e.Body.Replace("[addilang]", string.Empty);
        //}
    }

    /// <summary>
    /// Replaces the [addilang] string with a hyperlink to the translation of the post.
    /// </summary>
    private static void AddAddiLangLink(object sender, ServingEventArgs e)
    {
        Post post = (Post)sender;
        int index = e.Body.IndexOf("[addilang]"); 
        StringBuilder link = new StringBuilder();
        string flag = _settings.GetSingleValue("flag");

        link.Append("<a href=\"" + post.RelativeLink + "#addilang\">");
        link.Append(_settings.GetSingleValue("alternatelanguagetext"));
        
        link.Append("</a>");

        // TODO: Add code to check if file exists
        if (flag != String.Empty)
            link.AppendFormat(" <img src=\"{0}\" title=\"{1}\" alt=\"{1}\" />",
                Utils.AbsoluteWebRoot + "/pics/flags/" + flag,
                _settings.GetSingleValue("alternatelanguagetext"));

        e.Body = link.ToString() + e.Body.Substring(0, index);
    }

    /// <summary>
    /// Replaces the [addilang] string on the full post page.
    /// </summary>
    private static void PrepareFullPost(ServingEventArgs e)
    {
        //HttpRequest request = HttpContext.Current.Request;
        //if (request.UrlReferrer == null || request.UrlReferrer.Host != request.Url.Host)
        //{
        //    e.Body = e.Body.Replace("[addilang]", string.Empty);
        //}
        //else
        //{
        //    e.Body = e.Body.Replace("[addilang]", "<span id=\"addilang\"></span>");
        //}
        StringBuilder s = new StringBuilder();
        string flag = _settings.GetSingleValue("flag");

        if (flag != string.Empty)
        {
            s.AppendFormat("<p></p><span id=\"addilang\"><img src=\"{0}\" title=\"{1}\" alt=\"{1}\" /></span>",
                Utils.AbsoluteWebRoot + "/pics/flags/" + flag,
                _settings.GetSingleValue("alternatelanguagetext"));
            
            e.Body = e.Body.Replace("[addilang]", s.ToString());
        }
        else
        {
            e.Body = e.Body.Replace("[addilang]", "<span id=\"addilang\"></span>");
        }
    }
}
